package cn.jietuo.juc.c_000;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/2
 * @description: Sleep_Yield_Join
 */
public class T03_Sleep_Yield_Join {

    public static void main(String[] args) {
//        testSleep();
//        testYiled();
        testJoin();
    }

    static void testSleep() {
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("testSleep:" + i);
                try {
                    TimeUnit.MICROSECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    static void testYiled(){
       new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println("testYiled1:" + i);
                if (i % 10 == 10){
                    Thread.yield();
                }
            }
        }).start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                System.out.println("testYiled2:" + i);
                if (i % 10 == 10){
                    Thread.yield();
                }
            }
        }).start();
    }

    static void testJoin(){
        Thread thread1 = new Thread(() -> {
            for(int i =0;i < 10;i ++){
                System.out.println("testJoin1:" + i);
                try {
                    new Object().wait();
                    TimeUnit.MICROSECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for(int i =0;i < 10;i ++){
                System.out.println("testJoin2:" + i);
                if (i == 3){
                    try {
                        thread1.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    TimeUnit.MICROSECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
